# -*- coding:utf-8 -*-
"""
@Time : 2020-12-15 11:54
@Author: langengel
@Des: 服务商登录
"""

from Authorization.auth import create_access_token
from config.security import ACCESS_TOKEN_EXPIRE_MINUTES
from models.base import User
from core.response.BaseResponse import success, fail
from core.utils.utils import check_password
from validator.base import AdminLogin
from fastapi import Request


async def out_login():

    return success(msg="已退出登陆")


async def admin_login(req: Request, post: AdminLogin):
    """
    管理员用户登录
    :param req: Request
    :param post:
    :return:
    """
    user = await User().get_or_none(u_phone=post.u_phone)
    if not user:
        return fail(msg="用户不存在或密码不正确")

    if not check_password(post.password, user.password):
        return fail(msg="用户不存在或密码不正确")

    # 用户是否激活
    if user.u_status == 0:
        return fail(msg="管理员账户未激活")

    # 用户是否禁用
    if user.u_status != 1:
        return fail(msg="账户已停用")

    # 封装jwt data

    token_data = {
        "user": user.pk,
        "is_admin": user.type,
    }

    # 更新访问IP
    await User().filter(pk=user.pk).update(client_host=req.client.host)

    # 生成jwt token
    access_token = create_access_token(data=token_data)

    return success(
        data={
            "access_token": access_token,
            "expires_in": ACCESS_TOKEN_EXPIRE_MINUTES * 60,
            "token_type": "bearer",
        },
        msg="登录成功"

    )
